package com.huayi.server.NioServer;

import com.huayi.server.Entity.DeviceEntity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Locale;

/**
 * Created by mac on 2017/8/22.
 */
public class MessageEncode extends MessageToByteEncoder<Message>{

    Logger logger = LoggerFactory.getLogger(MessageEncode.class);

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {

        try{
            byteBuf.writeByte(0);
            int startIndex = byteBuf.writerIndex();//length
            byteBuf.writeShort(0);
            byteBuf.writeByte(message.getKey());
            byteBuf.writeByte(message.getAck());
            byteBuf.writeByte(message.getApi());
            switch (message.getApi()){
                case 1://Message.CONTROL
                    byteBuf.writeByte(message.getData_len());//心跳没有这一个值
                    for (DeviceEntity device:message.getDevicelist()) {
                        byteBuf.writeBytes(Unpooled.copiedBuffer(device.getDeviceId().getBytes()));
                        byteBuf.writeByte(device.getOpen()?2:1);//赵工2开1关
                        byteBuf.writeShort(device.getTime());
                    }
                    break;
                case 3://Message.CONFIG
                    byteBuf.writeByte(message.getData_len());//心跳没有这一个值
                    for (DeviceEntity device:message.getDevicelist()) {
                        byteBuf.writeBytes(Unpooled.copiedBuffer(device.getDeviceId().getBytes()));
                        byteBuf.writeShort((device.getAT()+50)*10);
                        byteBuf.writeByte(device.getAH());
                        byteBuf.writeBoolean(device.getAutoTmpFlag());
                        byteBuf.writeBoolean(device.getAutoHumFlag());
                    }
                    break;
                case 5:
                    logger.error("heart...");
                    break;
                default:
                    logger.error("type error ...");
                    break;
            }
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            byteBuf.resetReaderIndex();
            int xor = 0;
            for (byte b :bytes){
                xor = xor|b;
            }
            byteBuf.writeByte(xor);
            int endIndex = byteBuf.writerIndex();
            //logger.error("startindex:"+startIndex+",endindex:"+endIndex);
            byteBuf.setShort(startIndex,endIndex-startIndex);
            byteBuf.setByte(0,0xc0);
            byteBuf.writeByte(0xc0);
//            logger.info("byteBuf:"+byte2hex(byteBuf));

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private static String byte2hex(ByteBuf buf){
        buf.resetReaderIndex();
        StringBuilder h = new StringBuilder();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        for (int i = 0;i<bytes.length;i++){
            String b;
            if (bytes[i]<=10 && bytes[i]>=0){
                b = String.format(Locale.getDefault(), " 0%X", bytes[i]);
            }else{
                b = String.format(Locale.getDefault(), " %X", bytes[i]);
            }
            h.append(b);
        }
        return h.toString();
    }
}